package com.erp.popupwin

import android.content.Context
import android.content.SharedPreferences
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.*
import android.widget.BaseAdapter
import android.widget.PopupWindow
import android.widget.TextView
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.bean.BypassBean
import com.erp.util.Httputil
import com.erp.util.JsonUtil
import com.erp.util.Myutil
import kotlinx.android.synthetic.main.lv_duoxuan_item.view.*
import kotlinx.android.synthetic.main.pop_sheji_xiaoshou_duoxuan.view.*
import org.json.JSONArray
import org.json.JSONObject

/**
 * Created by Administrator on 2018/5/29/029.
 * 作者：刘洋
 */
class PopShejiXiaoshouDuoxuan(val context: Context,val code : Int ,val shejishi: MutableList<String>, val duoxuani: duoxuan, val title: String) {
    lateinit var mlist: MutableList<BypassBean>
    lateinit var mlistnew: MutableList<BypassBean>
    lateinit var mxuanzhong: MutableList<String>
    lateinit var mxuanzhongid: MutableList<String>
    lateinit var adapter: DuoxuanAdapter
    lateinit var tv: TextView
    var isdan = false

    companion object {
        var datas = ""
        var jingli = ""
        val XSY = 1
        val JL = 2
        val TF = 3
    }

    fun dan(dan: Boolean) {
        this.isdan = dan
    }

    fun show(sp: SharedPreferences, ytv: TextView) {
        mlist = ArrayList()
        mlistnew = ArrayList()
        mxuanzhong = ArrayList()
        mxuanzhongid = ArrayList()
        val popupWindow = PopupWindow(context)
        val rootView = LayoutInflater.from(context).inflate(R.layout.pop_sheji_xiaoshou_duoxuan, null, false)
        adapter = DuoxuanAdapter(mlistnew, context, mxuanzhong)
        rootView.LvName.adapter = adapter
        rootView.LvName.setOnItemClickListener { parent, view, position, id ->
            if (mxuanzhong.contains(mlistnew[position].name)) {
                mxuanzhong.remove(mlistnew[position].name)
                mxuanzhongid.remove(mlistnew[position].uid)
            } else {
                if (isdan) {
                    mxuanzhong.clear()
                    mxuanzhongid.clear()
                }
                mxuanzhong.add(mlistnew[position].name)
                mxuanzhongid.add(mlistnew[position].uid)
            }
            tvxuanzhong()
            adapter.notifyDataSetChanged()
        }
        rootView.BtQueding.setOnClickListener {
            popupWindow.dismiss()
            duoxuani.xuanze(mxuanzhong, mxuanzhongid)
        }
        rootView.TvTitle.text = title
        tv = rootView.TvXuanzhong
        popupWindow.contentView = rootView
        popupWindow.isFocusable = true
        popupWindow.isOutsideTouchable = true
        popupWindow.width = ViewGroup.LayoutParams.MATCH_PARENT
        popupWindow.height = sp.getInt("height", 0) * 7 / 10
        popupWindow.showAtLocation(ytv, Gravity.BOTTOM, 0, 0)
        httpdata()
//        production_dispatch_execute
//        production_execut_properly
//        production_dispatch_view
//        production_dispatch_control
//        production_dispatch_accomplish
//        production_dispatch_execute
        rootView.EtShaixuan.addTextChangedListener(object : TextWatcher{
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                mlistnew.clear()
                for (b in mlist){
                    if(b.name.indexOf(s.toString()) !=  -1){
                        mlistnew.add(b)
                    }
                }
                adapter.notifyDataSetChanged()
            }
        })

    }

    fun tvxuanzhong() {
        val xuanzhong = StringBuffer("")
        for (s in mxuanzhong) {
            xuanzhong.append(s).append("  ")
        }
        Myutil.settv(xuanzhong.toString(), tv)
    }

    fun httpdata() {
        when (code) {
            XSY -> {
                if (datas == "") {
                    Httputil.getHttpBypass(context, 0, 50, object : OnUserDataInterface {
                        override fun onUserData(data: String) {
                            Log.d("TAAG", "data=$data")
                            datas = data
                            jsonclaen(data)
                        }

                        override fun onNot(throwable: String) {
                            Myutil.MyTost("获取数据失败")
                        }
                    })
                } else {
                    jsonclaen(datas)
                }
            }
            JL -> {
                if (jingli == "") {
                    Httputil.getmanager(context, object : OnUserDataInterface {
                        override fun onUserData(data: String) {
                            Log.d("TAAG", "data=$data")
                            jingli = data
                            jingliclaen(jingli)
                        }

                        override fun onNot(throwable: String) {
                            Myutil.MyTost("获取数据失败")
                        }
                    })
                } else {
                    jingliclaen(jingli)
                }
            }
            TF -> {
                tefudata()
            }
        }
    }
    //获取特服的数据
    private fun tefudata(){
        val names = arrayOf("新开专卖店", "新店第一单", "旧店换样", "加急单")
        for(i in 0 until names.size){
            val bypassBean = BypassBean()
            bypassBean.uid = i.toString()
            bypassBean.name = names[i]
            mlist.add(bypassBean)
        }
        for (b in mlist) {
            for (s in shejishi) {
                if (s.indexOf(b.name) != -1) {
                    mxuanzhong.add(b.name)
                    mxuanzhongid.add(b.uid)
                }
            }

        }
        tvxuanzhong()

        adapter.notifyDataSetChanged()
    }
    //解析员工网络数据
    private fun jsonclaen(data: String) {
        try {
            val js = JSONArray(data)
            for (i in 0 until js.length()) {
                val jo = js.get(i) as JSONObject
                val bypassBean = BypassBean()
                bypassBean.uid = JsonUtil.getvolue(jo, "uid")
                bypassBean.name = jo.getString("name")
                mlist.add(bypassBean)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        for (b in mlist) {
            for (s in shejishi) {
                if (s.indexOf(b.name) != -1) {
                    mxuanzhong.add(b.name)
                    mxuanzhongid.add(b.uid)
                }
            }
            mlistnew.add(b)
        }
        tvxuanzhong()
        adapter.notifyDataSetChanged()
    }
    //解析经理网络数据
    private fun jingliclaen(data: String) {
        try {
            val jo = JSONObject(data)
            val keys = jo.keys()
            while (keys.hasNext()) {
                val key = keys.next() as String
                val bypassBean = BypassBean()
                bypassBean.uid = key
                bypassBean.name = jo.getString(key)
                mlist.add(bypassBean)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        for (b in mlist) {
            for (s in shejishi) {
                if (s==b.name) {
                    mxuanzhong.add(b.name)
                    mxuanzhongid.add(b.uid)
                }
            }
            mlistnew.add(b)
        }
        tvxuanzhong()
        adapter.notifyDataSetChanged()
    }

    interface duoxuan {
        fun xuanze(list: MutableList<String>, listid: MutableList<String>)
    }
    class DuoxuanAdapter(val mlist: MutableList<BypassBean>, val context: Context, val mxuanzhong: MutableList<String>) : BaseAdapter() {
        var minflater: LayoutInflater = LayoutInflater.from(context)
        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            var v: View
            var h: ViewHeader
            if (convertView == null) {
                v = minflater.inflate(R.layout.lv_duoxuan_item, null)
                h = ViewHeader(v)
                v.tag = h
            } else {
                v = convertView
                h = v.tag as ViewHeader
            }
            var x = false
            for (s in mxuanzhong) {
                if (s == mlist[position].name) {
                    x = true
                    break
                }
            }
            h.cb.isChecked = x
            Myutil.settv(mlist[position].name, h.tv)
            return v
        }

        override fun getItem(position: Int): Any {
            return mlist.get(position)
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getCount(): Int {
            return mlist.size
        }

        class ViewHeader(v: View) {
            val tv = v.TvName
            val cb = v.CbXuan
        }
    }
}